package cn.edu.scau.cmi.wusonglang.orm.dao;


import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import cn.edu.scau.cmi.wusonglang.orm.entity.Student;

public class StudentDAO {

    private  Configuration configuration;

    private  SessionFactory factory;

    private  Session session;

    public Student findStudentById(int id) {
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        Student student = (Student) session.get(Student.class, id);
        transaction.commit();
        session.close();
        configuration = new Configuration();
        //configuration.configure().addClass(User.class);
        configuration.configure("classpath:./hibernate.cfg.xml");
        factory = configuration.buildSessionFactory();
        return student;
    }

    public Student findStudentByName(String name){
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        Query query = session.createQuery("FROM Student Where name = ?1");
        query.setParameter(1,name);
        List<Student> list = query.list();
        transaction.commit();
        session.close();
        return list.get(0);
    }

    public void newStudent(Student student){
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        session.save(student);
        transaction.commit();
        session.close();
    }

    public void updateStudent(Student student){
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        session.update(student);
        transaction.commit();
        session.close();
    }

    public List<Student> findAllStudent(){
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        Query query = session.createQuery("FROM Student");
        List<Student> list = query.list();
        transaction.commit();
        session.close();
        return list;
    }

    public void deleteStudent(Student student){
        session = factory.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        session.delete(student);
        transaction.commit();
        session.close();
    }
}
